<template>
  <div class="person">
    <!-- v-model是v-model:value的简写，用于双向绑定数据; :value是v-bind:value的简写，用于绑定数据(单向绑定) -->
    姓：<input type="text" v-model="firstName"> <br>
    名：<input type="text" v-model="lastName"> <br>
    <button @click="changeFullName">将全名改为Li-Si</button> <br>
    <!-- vue官方建议，不要在模板中写太多逻辑，逻辑应该写在script标签中，让模板简单 -->
    <!-- 全名：<span>{{ firstName }}-{{ lastName }}</span> <br> -->
    全名：<span>{{ fullName }}</span> <br>
    全名：<span>{{ fullName }}</span> <br>
    全名：<span>{{ fullName }}</span> <br>
    全名：<span>{{ fullName2() }}</span> <br>
    全名：<span>{{ fullName2() }}</span> <br>
    全名：<span>{{ fullName2() }}</span> <br>
  </div>
  
</template>

<script lang="ts" setup name="Person">
import {ref, computed} from 'vue'

let firstName = ref('zhang')
let lastName = ref('san')

function fullName2() {
  console.log(2)
  return firstName.value.slice(0, 1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
}

// 计算属性computed有缓存，普通方法没有缓存
// 这么定义的fullName是一个计算属性，且是只读的,即不能fullName = 'abc'这样修改值
// let fullName = computed(() => {
//   console.log(1)
//   return firstName.value.slice(0, 1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
// })

// function changeFullName() {
//   console.log(fullName)
//   // Cannot assign to 'value' because it is a read-only property.t
//   fullName.value = 'Li-Si'
// }

// 这么定义的fullName是一个计算属性，可读可写
let fullName = computed({
  get() {
    return firstName.value.slice(0, 1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
  },
  set(val) {
    console.log('set fullName: ', val)
    let [firstNameVal, lastNameVal] = val.split('-')
    firstName.value = firstNameVal
    lastName.value = lastNameVal
  }
})

function changeFullName() {
  // 引起set()调用
  fullName.value = 'Li-Si'
}


</script>

<style scoped>
.person {
  background-color: skyblue;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px
}

button {
  margin: 0 5px;
}
li {
  font-size: 20px;
}
</style>